package engine.gui;

import engine.game.Manager;

public class Grid extends Panel {

	private static final long serialVersionUID = 1L;

	protected GridField[][] boxes ; 
	protected int rows = 1, cols = 1, cellspacing = 0; 
	
	public Grid(Manager m, ParentObject parent, int w, int h, int cols, int rows) {
		super(m, parent, w, h);
		this.rows = rows ; 
		this.cols = cols ; 
		init(); 
	}
	
	public Grid(Manager m, ParentObject parent, int w, int h, int cols, int rows, int cellspacing) {
		this(m, parent, w, h, cols, rows);
		this.cellspacing = cellspacing ; 
		init(); 
	}
	
	public GridField[][] getBoxes() {
		return boxes;
	}
	
	public GridField getFirstEmptyBox(){
		for(int y=0; y<this.getRows(); y++)
			for(int x=0; x<this.getCols(); x++)
				if(!this.boxes[x][y].hasContent())
					return this.boxes[x][y] ; 
		return null ; 
	}
	
	public boolean hasEmptyBox(){
		for(GridField[] f1: boxes)
			for(GridField f2: f1)
				if(!f2.hasContent())
					return true ; 
		return false ; 
	}
	
	public int getRows() {
		return rows;
	}
	
	public int getCols() {
		return cols;
	}

	public void init(){
		super.init();
		this.initFields(); 
	}
	
	protected void initFields(){
		if(cols == 0 || rows == 0) return ; 
		boxes = new GridField[cols][rows];
		int bw = this.getObjectWidth() / cols - cellspacing / 2;
		int bh = this.getObjectHeight() / rows - cellspacing / 2;
		int id = 0 ; 
		for (int x = 0; x < cols; x++) {
			for (int y = 0; y < rows; y++) {
				GridField tmp = new GridField(this.getManager(), this, bw, bh, id);
				tmp.padding(x*(bw+cellspacing/2), y*(bh+cellspacing/2));
				boxes[x][y] = tmp ; 
				this.addNewChild("box("+x+"|"+y+")", boxes[x][y]);
				id++ ; 
			}
		}
	}
	
	public void padding(int paddingLeft, int paddingTop){
		super.padding(paddingLeft, paddingTop);
		for(GridField[] o1: boxes)
			for(GridField o2: o1)
				o2.padding(paddingLeft, paddingTop);
	}	

	public void cellspacing(int cellspacing){
		this.cellspacing = cellspacing ; 
		int c = this.cellspacing / 2 ;
		for(int x=0; x<cols; x++)
			for(int y=0; y<rows; y++){
				int w = this.boxes[x][y].getObjectWidth() - c; 
				int h = this.boxes[x][y].getObjectHeight() - c; 
				this.boxes[x][y].padding(c, c); 
				this.boxes[x][y].changeSize(w, h);
			}
	}
	
}
